package wx;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * （微信定时发送消息）一个java文件，完成可配置的微信定时发送消息任务
 * https://blog.csdn.net/languageStudent/article/details/122123484
 * 基于Java实现的定时给微信好友发送消息
 * https://blog.csdn.net/qq_44085437/article/details/127888757
 * java awt 实现微信定时发送消息 https://blog.csdn.net/weixin_39209728/article/details/131515483
 */
public class SearchMyFriendAndSend {

    public static void main(String[] args) throws Exception {
        int weChat = queryProcessCount("WeChat");
        if (weChat <= 0) {
            System.err.println("请登陆微信后再尝试运行");
            return;
        }

        searchMyFriendAndSend("文件传输助手");
    }

    private static int queryProcessCount(String processName) throws IOException {
        int count = 0;
        Runtime runtime = Runtime.getRuntime();
        java.util.List<String> taskList = new ArrayList<>();
        Process process = runtime.exec("tasklist");
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s;
        while ((s = br.readLine()) != null) {
            if ("".equals(s)) {
                continue;
            }
            taskList.add(s);
        }
        for (String taskName : taskList) {
            if (taskName.contains(processName)) {
                count++;
            }
        }
        return count;
    }

    private static void searchMyFriendAndSend(String friendNickName) throws Exception {
        // 创建Robot对象
        Robot robot = getRobot();
        //打开微信 Ctrl+Alt+W
        assert robot != null;
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_W);
        //释放Ctrl按键，像Ctrl，退格键，删除键这样的功能性按键，在按下后一定要释放
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_ALT);

        // 该延迟不能少，否则无法搜索
        robot.delay(1000);

        // Ctrl + F 搜索指定好友
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_F);
        robot.keyRelease(KeyEvent.VK_CONTROL);

        // 将好友昵称发送到剪切板
        setSysClipboardText(friendNickName);

        // 以下两行按下了ctrl+v，完成粘贴功能
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.delay(1000);

        // 发送消息
        sendMsg();

        //关闭微信对话窗口
        robot.delay(2000);
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_F4);
        robot.keyRelease(KeyEvent.VK_ALT);
    }

    /**
     * 将字符串复制到剪切板 文本消息
     *
     * @param textStr
     */
    public static void setSysClipboardText(String textStr) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(textStr);
        clip.setContents(tText, null);
    }

    /**
     * 将文件复制到剪切板 图片消息
     * java 复制文件到 系统剪切板 https://blog.51cto.com/u_16099270/6927491
     * javaGUI学习32：AWT-剪贴板与数据传输 https://blog.csdn.net/qq_43464558/article/details/113549537
     *
     * @param imageUrl
     * @throws IOException
     */
    public static void setSysClipboardImg(String imageUrl) throws IOException {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (imageUrl.contains("\\")) {
            imageUrl = imageUrl.replace("\\", "/");
        }
        imageUrl = imageUrl.replace("img(", "");
        imageUrl = imageUrl.substring(0, imageUrl.length() - 1);
        Image image = ImageIO.read(new File(imageUrl));

        Transferable trans = new Transferable() {
            // 返回表示要传输的数据的对象
            @Override
            public Object getTransferData(DataFlavor flavor)
                    throws UnsupportedFlavorException {
                if (isDataFlavorSupported(flavor)) {
                    return image;
                }
                throw new UnsupportedFlavorException(flavor);
            }

            // 返回DataFlavor对象的数组，指示可以提供数据的风格
            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.imageFlavor};
            }

            // 返回此对象是否支持指定的数据flavor
            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(flavor);
            }
        };
        clip.setContents(trans, null);
    }

    /**
     * Java将文件复制到剪切板 https://blog.csdn.net/so185582/article/details/7700576
     * @param fileUrl
     * @throws IOException
     */
    public static void setSysClipboardFile(String fileUrl) throws IOException {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (fileUrl.contains("\\")) {
            fileUrl = fileUrl.replace("\\", "/");
        }
        fileUrl = fileUrl.replace("file(", "");
        fileUrl = fileUrl.substring(0, fileUrl.length() - 1);

        java.util.List<File> files = new ArrayList();
        files.add(new File(fileUrl));

        Transferable trans = new Transferable() {

            DataFlavor[] dataFlavors = new DataFlavor[]{DataFlavor.javaFileListFlavor};

            // 返回表示要传输的数据的对象
            @Override
            public Object getTransferData(DataFlavor flavor)
                    throws UnsupportedFlavorException {
                if (isDataFlavorSupported(flavor)) {
                    return files;
                }
                throw new UnsupportedFlavorException(flavor);
            }

            // 返回DataFlavor对象的数组，指示可以提供数据的风格
            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return dataFlavors;
            }

            // 返回此对象是否支持指定的数据flavor
            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                for (int i = 0; i < dataFlavors.length; i++) {
                    if (dataFlavors[i].equals(flavor)) {
                        return true;
                    }
                }
                return false;
            }
        };
        clip.setContents(trans, null);
    }

    private static void sendMsg() throws Exception {
        String[] mottoes = {
                "xdm，记得每天签到",
        };
        for (String motto : mottoes) {
            sendOneMsg(motto);
        }

        Thread.sleep(2000);
        sendOneMsg("学院要登记的哦！");

        Thread.sleep(2000);
        sendOneMsg("img(C:\\Users\\74102\\Pictures\\logo.jpg)");

        Thread.sleep(2000);
        sendOneMsg("file(C:\\Users\\74102\\Pictures\\f7d222debeb3dadab47f7e99e1b6b424.mp4)");

        Thread.sleep(2000);
        sendOneMsg("file(C:\\Users\\74102\\Downloads\\表单控件.xlsx)");
    }

    private static void sendOneMsg(String msg) throws Exception {
        // 创建Robot对象
        Robot robot = getRobot();
        if (msg.contains("img(")) {
            setSysClipboardImg(msg);
        } else if (msg.contains("file(")) {
            setSysClipboardFile(msg);
        } else {
            // 不能发送空白消息
            msg = msg.replace("\\n", "\n");
            // System.out.println("msg: " + msg);
            setSysClipboardText(msg);
        }

        robot.delay(1000);

        // 以下两行按下了ctrl+v，完成粘贴功能
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        // 回车发送
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.delay(1000);
    }

    private static Robot getRobot() {
        // 创建Robot对象
        Robot robot = null;
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
        return robot;
    }

}
